package com.chis.netty.mqtt.client;

import com.chis.netty.http.client.HttpsClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class MyTest {

	private static class TrustAnyTrustManager implements X509TrustManager {

		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}

	private static class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

	public void connect(int port, String host) throws Exception {
		// 网络事件处理线程组
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			// 配置客户端启动类
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							ChannelPipeline pipeline = socketChannel.pipeline();
							//mqtt协议
							pipeline.addLast("decoder", new MqttDecoder());
							pipeline.addLast("encoder", MqttEncoder.INSTANCE);
							pipeline.addLast(new BrokerHandler());//
							// ssl
							SSLContext sc = SSLContext.getInstance("SSL");
							sc.init(null, new TrustManager[] { new MyTest.TrustAnyTrustManager() },
									new java.security.SecureRandom());
							SSLEngine engine = sc.createSSLEngine();
							engine.setUseClientMode(true);
							pipeline.addFirst("ssl", new SslHandler(engine));
						}
					});

			Channel channel = b.connect(host, port).sync().channel();
			
			
			// 同步等待客户端通道关闭
			channel.closeFuture().sync();
		} finally {
			// 释放线程组资源
			group.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		int port = 9091;
		new MyTest().connect(port, "127.0.0.1");
	}


}
